<?php

namespace App\Http\Controllers\Web;


use App\FriendList;
use App\Http\Controllers\Controller;
use App\Http\Controllers\好友id;
use App\ImUser;
use App\Models\Api\v1\Friend;
use App\Models\Api\v1\Message;
use App\Models\User;
use App\Transformers\web\ImTransformer;
use GatewayClient\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use function dd;
use function redirect;
use function session;
use function view;


class ImController extends Controller
{
    /**
     * 好友列表
     */
    public function indexList()
    {
        $user = session('user');
        $data = User::query()->where('id', '<>', $user['id'])->get();
        $data = self::roleOnline($data);
        return view('im.indexList',['data'=>$data]);
    }

    protected static function roleOnline($data)
    {
        foreach ($data as $key => $val) {
            if ($data[$key]['role'] == 2) {
                $data[$key]['role_name'] = '客服';
            } else {
                $data[$key]['role_name'] = '用户';
            }
            //$onLine = Gateway::getClientIdByUid($data[$key]['id']);
            $onLine = 1;
            $data[$key]['status'] = $onLine ? '在线' : '不在线';
        }
        return $data;
    }


    /**
     * 绑定用户
     * @param Request $request
     */
    public function binding(Request $request)
    {
        $client_id = $request->client_id;
        $user = session('user');
        $uid = $user['id'];
        Gateway::bindUid($client_id, $uid);
        $message = [
            'type' => 'binding_success',
            'msg' => '绑定成功'
        ];
//        Gateway::$registerAddress = '127.0.0.1:1236';
        Gateway::sendToUid($uid, json_encode($message));
        $message['code'] = 200;
        $message['success'] = 1;//1:成功,0:失败
        return json_encode($message);
    }

    /**
     * 聊天页面
     * @param Request $request
     */
    public function chat(Request $request, $friend_id)
    {
        return view('im.chat', compact('friend_id'));
    }


    /**
     * 发送消息
     */
    public function sendMessage(Request $request)
    {
        $post = $request->all();
        $user = session('user');
        $user_id = $user['id'];
        $message = [
            'type' => $request->type,
            'addresser_id' => $user_id,
            'recipients_id' => $post['recipients_id'],
            'msg' => $post['msg'],
        ];

        Gateway::$registerAddress = '127.0.0.1:1236';
        Gateway::sendToUid($post['recipients_id'], json_encode($message));
        $message['code'] = 200;
        $message['success'] = 1;//1:成功,0:失败
        //储存聊天记录
        Message::createMessage($post['msg'], $post['recipients_id'], $user_id);
        return json_encode($message);
    }
}
